import time
import ssh
import os


class ServerManager:
    def __init__(self, ecs_client, server_config):
        self.ecs_client = ecs_client
        self.port = server_config.ss_port
        self.password = server_config.ss_password
        self.method = server_config.ss_method

    def create_alloc_start_install(self):
        try:
            security_group_id = self.ecs_client.create_valid_security_group()
            instance_id = self.ecs_client.create_instance(security_group_id=security_group_id)
            i = 0
            for i in range(0, 20):
                print 'wait stopped times', i
                instance = self.ecs_client.get_instance(instance_id)
                if instance.status == 'Stopped':
                    print 'instance status stopped'
                    i = 0
                    break
                time.sleep(3)

            if i is not 0:
                print 'Failed, please delete later'
                return

            self.ecs_client.alloc_ip(instance_id)
            instance = self.ecs_client.get_instance(instance_id)
            print 'instance ip is', instance.ip[0]

            self.ecs_client.start_instance(instance_id)

            for i in range(0, 10):
                print 'wait connecting times', i
                res = ssh.ssh_exec(instance.ip[0], 'root', self.ecs_client.password, 'echo hello')
                if res is not None:
                    print 'instance status connected'
                    i = 0
                    break
                time.sleep(6)

            if i is not 0:
                print 'Failed, try to delete'
                self.stop_delete(instance_id)
                return

            ssh.upload_dir_exec(instance.ip[0],
                                'root',
                                self.ecs_client.password,
                                os.path.join(os.path.split(os.path.realpath(__file__))[0], '..', 'shell'),
                                'sh install-game-server-auto.sh %d %s %s' % (self.port, self.password, self.method))
        except Exception, e:
            print 'exception: ', e

    def stop_delete_all(self):
        try:
            instances = self.ecs_client.get_instances()
            for instance in instances:
                instance_id = instance['InstanceId']
                self.stop_delete(instance_id)
                # try:
                #     security_group_id = instance['SecurityGroupIds']['SecurityGroupId'][0]
                #     print 'ready to delete security group...'
                #     time.sleep(5)
                #     ecs_client.delete_security_group(security_group_id)
                # except Exception, e:
                #     print 'exception:', e
            print 'delete all finish'
        except Exception, e:
            print 'exception:', e
            print 'please delete manually'
            return

    def stop_delete(self, instance_id):
        try:
            self.ecs_client.stop_instance(instance_id)
            i = 0
            for i in range(0, 20):
                print 'wait stopped times', i
                instance = self.ecs_client.get_instance(instance_id)
                if instance.status == 'Stopped':
                    print 'instance status stopped'
                    i = 0
                    break
                time.sleep(3)

            if i is not 0:
                print 'please delete manually'
                return

        except Exception, e:
            print 'exception:', e

        self.ecs_client.delete_instance(instance_id)

    def show_all(self):
        try:
            instances = self.ecs_client.get_instances()
            i = 0
            for instance in instances:
                instance_id = instance['InstanceId']
                i = i + 1
                print 'instance', i
                self.ecs_client.get_instance(instance_id).show()
            if i == 0:
                print 'no instance found'
        except Exception, e:
            print 'exception:', e
